package com.chenjiagou.controller;

import com.chenjiagou.pojo.Notification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/user")
public class NotificationController {
    @Autowired
    private com.chenjiagou.feign.NotificationFeignClient notificationFeignClient;

    @GetMapping("/notifications/{userId}")
    public String listNotifications(@PathVariable("userId") int userId,
                                    Model model,
                                    HttpSession session) {
        // 校验用户ID与Session中保存的是否一致，防止越权访问
        Integer sessionUserId = (Integer) session.getAttribute("userId");
        if (sessionUserId == null || sessionUserId != userId) {
            return "redirect:/login";
        }



        List<Notification> notifications = notificationFeignClient.findNotificationByUserId(userId);
        model.addAttribute("notifications", notifications);



        return "notificationlist";
    }

    @PostMapping("/notifications/{userId}/{notificationId}/read")
    public String markAsRead(@PathVariable("userId") int userId,
                             @PathVariable("notificationId") int notificationId,
                             HttpSession session) {
        Integer sessionUserId = (Integer) session.getAttribute("userId");
        if (sessionUserId == null || sessionUserId != userId) {
            return "redirect:/login";
        }

        notificationFeignClient.markAsRead(userId, notificationId);
        return "redirect:/user/notifications/" + userId;
    }


    @PostMapping("/notifications/{userId}/{notificationId}/delete")
    public String deleteNotification(@PathVariable("userId") int userId,
                                     @PathVariable("notificationId") int notificationId,
                                     HttpSession session) {
        Integer sessionUserId = (Integer) session.getAttribute("userId");
        if (sessionUserId == null || sessionUserId != userId) {
            return "redirect:/login";
        }

        // 调用删除接口
        notificationFeignClient.deleteNotification(notificationId);

        return "redirect:/user/notifications/" + userId;
    }

}